package com.ruoyi.common.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.oms.dao.YytOmsOrderItemMapper;
import com.ruoyi.common.oms.dao.YytOmsOrderSettingMapper;
import com.ruoyi.common.oms.entity.*;
import com.ruoyi.common.oms.dao.YytOmsOrderMapper;
import com.ruoyi.common.oms.service.YytOmsOrderReturnApplyService;
import com.ruoyi.common.oms.service.YytOmsOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.pms.dao.YytShopMemberMapper;
import com.ruoyi.common.pms.entity.*;
import com.ruoyi.common.pms.service.*;
import com.ruoyi.common.sys.entity.SysUserShop;
import com.ruoyi.common.sys.service.SysUserShopService;
import com.ruoyi.utils.LoginUtils;
import com.ruoyi.utils.RedisService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.update.UpdateRequest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author huangshun
 * @since 2021-12-16
 */
@Service
public class YytOmsOrderServiceImpl extends ServiceImpl<YytOmsOrderMapper, YytOmsOrder> implements YytOmsOrderService {

    @Autowired
    private YytOmsOrderMapper yytOmsOrderMapper;
    @Autowired
    private YytOmsOrderItemMapper yytOmsOrderItemMapper;
    @Autowired
    private YytOmsOrderSettingMapper yytOmsOrderSettingMapper;

    @Autowired
    private YytOmsOrderReturnApplyService yytOmsOrderReturnApplyService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysUserShopService sysUserShopService;

    @Autowired
    private YytShopService yytShopService;

    @Autowired
    private YytShopMemberService yytShopMemberService;

    @Autowired
    private YytShopMemberMapper yytShopMemberMapper;

    @Autowired
    private YytMaaSubscribeStoreService yytMaaSubscribeStoreService;

    @Autowired
    private YytMaaCraftsmanService yytMaaCraftsmanService;

    @Autowired
    private YytMaaServicesService yytMaaServicesService;

    /**
     * 根据用户id和订单状态获取订单数量
     */
    @Override
    public Integer countOrder(String memberId, int status) {
        return yytOmsOrderMapper.countOrder(memberId, status);
    }

    /**
     * 根据状态获取用户订单列表
     */
    @Override
    public Page<YytOmsOrder> getOrders(Page<YytOmsOrder> page, String memberId, Integer status) {
        LambdaQueryWrapper<YytOmsOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YytOmsOrder::getMemberId, memberId);
        wrapper.orderByDesc(YytOmsOrder::getCreateTime);
        wrapper.eq(YytOmsOrder::getDelFlag, 0);
        if (null != status) {
            wrapper.eq(YytOmsOrder::getStatus, status);
        }
        return yytOmsOrderMapper.getOrders(wrapper, page);
    }

    /**
     * 用户下单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(YytOmsOrder yytOmsOrder) {
        // 获取订单配置信息
        List<YytOmsOrderSetting> list = yytOmsOrderSettingMapper.selectPage(new Page<>(1, 1),
                new QueryWrapper<YytOmsOrderSetting>().orderByDesc("id")).getRecords();
        if (list.size() > 0) {
            YytOmsOrderSetting yytOmsOrderSetting = list.get(0);
            yytOmsOrder.setAutoConfirmDay(yytOmsOrderSetting.getConfirmOvertime());
            // TODO 设置redis订单超时时间
        }
        yytOmsOrder.setOrderSn(System.currentTimeMillis() + "");
        if (yytOmsOrderMapper.selectById(yytOmsOrder) == null) {
            yytOmsOrderMapper.insert(yytOmsOrder);
            for (YytOmsOrderItem item : yytOmsOrder.getItemList()) {
                item.setOrderId(yytOmsOrder.getId());
                item.setOrderSn(yytOmsOrder.getOrderSn());
                yytOmsOrderItemMapper.insert(item);
            }
        }
        return true;
    }

    /**
     * 根据订单id获取订单详情信息
     */
    @Override
    public YytOmsOrder getOrderInfo(String orderId, String memberId) {
        YytOmsOrder yytOmsOrder = yytOmsOrderMapper.selectById(orderId);
        // 掩盖真实电话
        String phone = yytOmsOrder.getReceiverPhone().substring(0, 3) + "****" + yytOmsOrder.getReceiverPhone().substring(7);
        yytOmsOrder.setReceiverPhone(phone);
//        if (!memberId.equals(yytOmsOrder.getMemberId())) {
//            return new YytOmsOrder();
//        }
        List<YytOmsOrderItem> detailList = yytOmsOrderItemMapper.getItemList(orderId);
        Map<String, Object> item = new HashMap<>(3);
        List<YytOmsOrderItem> itemList = new ArrayList<>();
        for (YytOmsOrderItem orderItem : detailList) {
            YytShop shop = orderItem.getShop();
            // 组装返回格式
            if (item.size() > 0 && shop.getId().equals(item.get("shopId"))) {
                itemList.add(orderItem);
            } else {
                item = new HashMap<>(3);
                item.put("shopId", shop.getId());
                item.put("shop", shop);
                itemList = new ArrayList<>();
                itemList.add(orderItem);
                item.put("detailList", itemList);
                yytOmsOrder.getDetailList().add(item);
            }
        }
        QueryWrapper<YytOmsOrderReturnApply> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        yytOmsOrder.setReturnList(yytOmsOrderReturnApplyService.list(wrapper));
        return yytOmsOrder;
    }


    @Override
    public boolean orderMessageQueue(String orderId) {
        rabbitTemplate.convertAndSend("yunya.order.direct.exchange","order",orderId);
        return true;
    }

    @Override
    public Map getDayCountNumber(String dayDate) {
        try {
            YytMember loginUser = LoginUtils.getLoginUser(redisService);
            return yytOmsOrderMapper.getDayCountNumber(loginUser.getId(), dayDate);
        }catch (Exception e){
            return new HashMap<>();
        }

    }

    @Override
    public Map<String, Object> getDayOrderListTitle(Page<YytOmsOrder> page, String dayDate) {
        YytMember loginUser = LoginUtils.getLoginUser(redisService);
        QueryWrapper<YytShopMember> wrapper = new QueryWrapper<>();
        wrapper.select("shop_id").eq("member_id", loginUser.getId());
        List<YytShopMember> list1 = yytShopMemberService.list(wrapper);
        List<String> lists = new ArrayList<>();
        for (YytShopMember ysm : list1){
            lists.add(ysm.getShopId());
        }
        QueryWrapper<YytShop> wrappers = new QueryWrapper<>();
        wrappers.eq("del_flag", 0).eq("state", 1).in("id", lists);
        List<YytShop> list = yytShopService.list(wrappers);
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        for (YytShop ys : list){
            Map<String, Object> ysMap = new HashMap<>();
            ysMap.put("state", ys.getId());
            ysMap.put("text", ys.getShopName());
            ysMap.put("loadingType", "more");
            ysMap.put("orderList", new ArrayList<>());
            result.add(ysMap);
        }
        resultMap.put("shopList", result);

//        List<String> shopIdList = list.stream().map(YytShop::getId).collect(Collectors.toList());
        if(list.size() > 0){
            List<String> shopIdList = new ArrayList<>();
            shopIdList.add(list.get(0).getId());
            List<YytOmsOrder> yytOmsOrders = yytOmsOrderMapper.getDayOrderList(shopIdList, dayDate);
            for (int i = 0; i < yytOmsOrders.size(); i++){
                QueryWrapper<YytOmsOrderItem> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_id", yytOmsOrders.get(i).getId());
                yytOmsOrders.get(i).setItemList(yytOmsOrderItemMapper.selectList(wrapper1));
            }
            resultMap.put("orders", yytOmsOrders);
        }else{
            resultMap.put("orders", null);
        }
        return resultMap;
    }

    @Override
    public List<YytOmsOrder> getShopDayOrderList(String shopId, String dayDate) {
        List<String> shopIdList = new ArrayList<>();
        shopIdList.add(shopId);
        List<YytOmsOrder> yytOmsOrders = yytOmsOrderMapper.getDayOrderList(shopIdList, dayDate);
        for (int i = 0; i < yytOmsOrders.size(); i++){
            QueryWrapper<YytOmsOrderItem> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", yytOmsOrders.get(i).getId());
            yytOmsOrders.get(i).setItemList(yytOmsOrderItemMapper.selectList(wrapper1));
        }
        return yytOmsOrders;
    }

    /**
     * 核销订单服务
     * @param orderId
     * @return
     */
    @Override
    public Boolean updateOrderStatus(String orderId) {
        YytMember loginUser = LoginUtils.getLoginUser(redisService);
        QueryWrapper<YytMaaCraftsman> wrapper = new QueryWrapper<>();
        wrapper.eq("wxid", loginUser.getWechatId()).last("limit 1");
        YytMaaCraftsman craftsman = yytMaaCraftsmanService.getOne(wrapper);
        // 查询服务预约数据
        QueryWrapper<YytMaaSubscribeStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId).last("limit 1");
        YytMaaSubscribeStore one = yytMaaSubscribeStoreService.getOne(queryWrapper);
        // 如果该订单已经核销
        if(one.getServiceTime() != null){
            return false;
        }
        // 修改订单表
        UpdateWrapper<YytOmsOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId).set("status", "3").set("confirm_status", "1").set("dispose_status", "1").set("receive_time", LocalDateTime.now());
        boolean update = super.update(updateWrapper);
        // 修改服务预约表
        UpdateWrapper<YytMaaSubscribeStore> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("order_id", orderId).set("service_time", LocalDateTime.now()).set("subscribe_state", "1");
        yytMaaSubscribeStoreService.update(updateWrapper1);
        // 新增服务记录
        YytMaaServices yytMaaServices = new YytMaaServices();
        yytMaaServices.setSubscribeId(one.getId());
        yytMaaServices.setCraftsmanId(craftsman.getId());
        yytMaaServices.setServeEndTime(LocalDateTime.now());
        yytMaaServicesService.save(yytMaaServices);

        return true;
    }

    /**
     * 获取当前人的当月订单
     * @param id
     * @return
     */
    @Override
    public List<YytOmsOrder> getMyMonthOrders(String id) {
        LambdaQueryWrapper<YytOmsOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(YytOmsOrder::getStatus, '0');
        wrapper.ne(YytOmsOrder::getStatus, '4');
//        wrapper.ne(YytOmsOrder::getStatus, '5');
        wrapper.eq(YytOmsOrder::getMemberId, id);
        // 因为是查本月，所以当前时间不会在下个月的时间 直接大于本月1号即可
        wrapper.ge(YytOmsOrder::getCreateTime, LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()));
        wrapper.orderByDesc(YytOmsOrder::getPaymentTime);
        List<YytOmsOrder> yytOmsOrders = yytOmsOrderMapper.selectList(wrapper);
        for (int i = 0; i < yytOmsOrders.size(); i++){
            QueryWrapper<YytOmsOrderItem> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", yytOmsOrders.get(i).getId());
            yytOmsOrders.get(i).setItemList(yytOmsOrderItemMapper.selectList(wrapper1));
        }
        return yytOmsOrders;
    }

    /**
     * 根据用户权限获取待核销订单
     * @param id
     * @return
     */
    @Override
    public List<YytOmsOrder> getAwaitOrderCancel(String id) {
        List<String> myShopList = yytShopMemberMapper.getMyShopList(id);
        if (myShopList.size() == 0){
            return new ArrayList<>();
        }
        List<YytOmsOrder> awaitOrderCancels = yytOmsOrderMapper.getAwaitOrderCancels(myShopList);
        for (int i = 0; i < awaitOrderCancels.size(); i++){
            QueryWrapper<YytOmsOrderItem> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", awaitOrderCancels.get(i).getId());
            awaitOrderCancels.get(i).setItemList(yytOmsOrderItemMapper.selectList(wrapper1));
        }
        return awaitOrderCancels;
    }


    /**
     * 公共获取用户绑定店铺数据
     * @return
     */
    public List<String> getUserShopList(){
        YytMember loginUser = LoginUtils.getLoginUser(redisService);
        QueryWrapper<SysUserShop> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", loginUser.getId());
        List<SysUserShop> list = sysUserShopService.list(wrapper);
        List<String> result = new ArrayList<>();
        for (SysUserShop shop:list){
            result.add(shop.getShopId());
        }
        return result;
    }
}
